package com.java.travel.controller;

import com.java.travel.entity.Province;
import com.java.travel.entity.Result;
import com.java.travel.service.ProvinceService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 * author:张腾
 * date:2021-03-08
 */

@RestController
@CrossOrigin
@RequestMapping("province")
@Api(tags = "省份模块")
public class ProvinceController {

    @Autowired
    private ProvinceService provinceService;

    /**
     * 查询所有
     * @param page
     * @param rows
     * @return
     */
    @GetMapping("findByPage")
    public Map<String,Object> findByPage(Integer page,Integer rows){
        page = page==null?1:page;
        rows = rows==null?4:rows;
        HashMap<String,Object> map = new HashMap<>();
        //分页处理
        List<Province> provinces = provinceService.findByPage(page,rows);
        //计算总页数
        Integer totals = provinceService.findTotals(); //总条数
        Integer totalPages = totals%rows==0?totals/rows:totals/rows+1;
        map.put("provinces",provinces);
        map.put("totals",totals);
        map.put("totalPages",totalPages);
        map.put("page",page);

        return map;
    }

    /**
     * 保存省份信息
     * @param province
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody Province province){
        Result result = new Result();
        try{
            provinceService.save(province);
            result.setMsg("保存省份信息成功！");
        }catch (Exception e){
            e.printStackTrace();
            result.setState(false).setMsg("保存省份信息失败！");
        }
        return result;
    }

    /**
     * 删除省份
     * @param id
     * @return
     */
    @GetMapping("delete")
    public Result delete(String id){
        Result result = new Result();
        try{
            provinceService.delete(id);
            result.setMsg("删除成功！");
        }catch (Exception e){
            e.printStackTrace();
            result.setState(false).setMsg("删除失败！");
        }
        return result;
    }

    @GetMapping("findOne")
    public Province findOne(String id){
        return provinceService.findOne(id);
    }

    /**
     * 修改省份信息
     * @param province
     * @return
     */
    @PostMapping("update")
    public Result updateProvince(@RequestBody Province province){
        Result result = new Result();
        try{
            provinceService.updateProvince(province);
            result.setMsg("修改省份信息成功！");
        }catch (Exception e){
            e.printStackTrace();
            result.setState(false).setMsg(e.getMessage());
        }
        return result;
    }
}
